//
//  ScoreSubmitParser.m
//  Politics
//
//  Created by Hai Nguyen on 7/9/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ScoreSubmitParser.h"


@implementation ScoreSubmitParser

@synthesize responseData;
@synthesize delegate;
@synthesize resultArray;

- (void)submitScore:(NSString *)userid score:(int) score withDelegate:(id)aDelegate
{
	delegate = aDelegate;
	responseData = [[NSMutableData data] retain];
	NSURL *baseURL = [[NSURL URLWithString:[NSString stringWithFormat:@"http://testsys.guncms.de/politicsgames/xml/save_score.php?username=%@&score=%d",userid,score]] retain];
	
	NSLog(@"%@",baseURL);
	
	NSURLRequest *request = [NSURLRequest requestWithURL:baseURL];
	
	[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [responseData setLength:0];
	
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSString * errorString = [NSString stringWithFormat:@"Unable to download xml data (Error code %i )", [error code]];
	
    UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{	
	NSXMLParser *rssParser = [[NSXMLParser alloc] initWithData:responseData];
	
	
	[rssParser setDelegate:self];
	
	[rssParser parse];
	NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	NSLog(@"login return %@",result);
	int resultValue = 0;
	resultValue = [result intValue];	
	if ([delegate respondsToSelector:@selector(didEndSubmit:)])
	{		
		NSLog(@"send delegate");
		[delegate didEndSubmit:resultArray];
		[resultArray removeAllObjects];
		[resultArray release];
	}
    else
    { 
		return;
        [NSException raise:NSInternalInconsistencyException
					format:@"Delegate doesn't respond to receivedNews:"];
    }
}

#pragma mark rssParser methods

- (void)parserDidStartDocument:(NSXMLParser *)parser {
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
	
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
	
	
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
	
}

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
	
}


- (void)dealloc 
{
	
	[responseData release];
	[super dealloc];
}


@end
